package com.dream.technology.components.engine;

import com.alibaba.fastjson.JSONArray;
import com.dream.technology.components.context.FlowContext;
import com.dream.technology.utils.parse.MapUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 描述：流程引擎
 *
 * @author chen_q_i@163.com
 * 2018/12/26 : 16:08.
 * @version : 1.0
 */
public final class FlowEngine {


   static  Pattern p = Pattern.compile("(?<=\\()(.+?)(?=\\))");

    /**
     * 进行流程的匹配和执行
     *
     * @param flowContext
     * @return
     */
    public static String startAnFlow(final FlowContext flowContext) {
        return "";
    }


    /**
     * 通过初始化输入，数据库服务，请求单数据构造流程运行的上下文
     *
     * @return
     */
    public static FlowContext createFlowContext(Map<String, Object> customer, Map<String, Object> orderForm) {

        FlowContext flowContext = new FlowContext();
        flowContext.put(FlowContext.CUSTOMER, customer);
        flowContext.put(FlowContext.ORDERFORM, orderForm);

        flowContext.putServiceNames(FlowContext.CUSTOMER);
        flowContext.putServiceNames(FlowContext.ORDERFORM);
        flowContext.putStartDate();
        return flowContext;
    }
    public static Map<String,String> getExpMap(String msg) {
        List<String> list = extractMessageByRegular(msg);
        Map<String, String> collect = list.stream().collect(Collectors.toMap(k -> "arr" + String.valueOf(k.hashCode()), k -> k));
        return collect;
    }

    public static String getNewExp(String msg){
        List<String> list = extractMessageByRegular(msg);
        for (String s : list) {
            String hashCode = String.valueOf(s.hashCode());
            String replacement = "arr" + hashCode;
            msg = msg.replace("(" + s + ")", replacement);
        }
        return msg;
    }

    /**
     * 使用正则表达式提取中括号中的内容
     * @param msg
     * @return
     */
    public static List<String> extractMessageByRegular(String msg){

        List<String> list=new ArrayList<String>();

        Matcher m = p.matcher(msg);
        while(m.find()){
            String substring = m.group();
            list.add(substring);
        }
        return list;
    }




    /**
     * 获取联系人和 银行卡号
     *
     * @param context
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public static  <T> List<T> getListFormHolder(FlowContext context, String key, Class<T> clazz) {

        List<Map> maps = (List<Map>) context.get(key);
        List<T> collect = maps.stream().map(x -> {
            try {
                return MapUtils.mapToBean(clazz, x);
            } catch (Exception e) {
                return null;
            }

        }).collect(Collectors.toList());

        return  collect;
    }


}
